import tkinter as tk
from tkinter import ttk
import time

import datetime
def get_previous_hour_millis() -> int:
    current_time = datetime.datetime.now()
    # 获取当前小时的起始时间（分钟、秒、微秒置零）
    current_floor = current_time.replace(minute=0, second=0, microsecond=0)
    print(f"当前时间的整点: {current_floor}")

    # 判断是否正好是整点cd

    previous_floor = current_floor - datetime.timedelta(hours=1)

    print(f"当前时间的上一个整点: {previous_floor}")

    # 计算时间戳并转换为毫秒数
    timestamp = previous_floor.timestamp()
    millis = int(timestamp * 1000)
    return millis
def generate_url():
    last_hour_timestamp = get_previous_hour_millis()
    env = env_var.get()
    tenant_id = tenant_var.get() or ('22454519199072' if env == 'cd' else '')
    entity_id = '19'
    data_id = data_id_var.get() or ''
    param_type = param_type_var.get() or 'quantity'
    value = value_var.get() or '5'

    url = f"https://crm-{env}.xiaoshouyi.com/admin/otcupgrade/update-objectData.action" \
        f"?updateTenatId={tenant_id}&otcTimestamp={last_hour_timestamp}" \
        f"&objectId={entity_id}&dataId={data_id}&apiKey={param_type}&value={value}"
    result_text.delete('1.0', tk.END)
    result_text.insert('1.0', url)
    result_text.tag_add('select', '1.0', 'end')

def copy_url():
    url = result_text.get('1.0', 'end').strip()
    root.clipboard_clear()
    root.clipboard_append(url)
    tk.messagebox.showinfo("复制成功", f"已复制完整URL: {url}")
def get_previous_hour_millis():
    current_time = datetime.datetime.now()
    # 获取当前小时的起始时间（分钟、秒、微秒置零）
    current_floor = current_time.replace(minute=0, second=0, microsecond=0)
    print(f"当前时间的整点: {current_floor}")

    # 判断是否正好是整点

    previous_floor = current_floor - datetime.timedelta(hours=1)

    print(f"当前时间的上一个整点: {previous_floor}")

    # 计算时间戳并转换为毫秒数
    timestamp = previous_floor.timestamp()
    millis = int(timestamp * 1000)
    return millis
# 主窗口初始化
root = tk.Tk()
root.title("智能URL生成器 v3.0")
root.geometry("800x600")  # 增大窗口尺寸以适应换行显示
root.resizable(False, False)

# 全局变量定义
env_var = tk.StringVar(value='cd')
tenant_var = tk.StringVar(value='')  # 用户可编辑
data_id_var = tk.StringVar(value='')
param_type_var = tk.StringVar(value='quantity')
value_var = tk.StringVar(value='5')

# 主框架布局（使用网格布局更清晰）
main_frame = ttk.Frame(root, padding="10")
main_frame.pack(fill=tk.BOTH, expand=True)

# 左侧配置区（基础信息+对象参数）
left_col = ttk.Frame(main_frame, width=300)
left_col.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

# 基础配置模块
base_frame = ttk.LabelFrame(left_col, text="基础配置")
base_frame.pack(fill=tk.BOTH, expand=True)

env_combobox = ttk.Combobox(
    base_frame, textvariable=env_var,
    values=['cd', 'tencentuat', 'test', 'gray', 'p06', 'p05','mrcd'], state='readonly'
)
env_combobox.pack(pady=5)

# 租户ID输入框（始终可编辑，cd环境有默认值）
tenant_label = ttk.Label(base_frame, text="租户ID:")
tenant_entry = ttk.Entry(
    base_frame, textvariable=tenant_var, width=20
)
tenant_label.pack(pady=5)
tenant_entry.pack(pady=5)
# 设置cd环境默认值
if env_var.get() == 'cd':
    tenant_entry.insert(0, '2245451914199072')

# 时间戳显示模块（固定在顶部）
timestamp_frame = ttk.Frame(left_col, height=50)
timestamp_frame.pack(pady=10)

timestamp_label = tk.Label(timestamp_frame, text="上一个整点毫秒:", font=('Arial', 10, 'bold'))
timestamp_value = tk.Label(timestamp_frame, text=f"{get_previous_hour_millis()}",
                           font=('Arial', 10, 'bold'), fg='#2ecc71')
timestamp_label.pack(side=tk.LEFT, anchor='nw')
timestamp_value.pack(side=tk.LEFT, anchor='ne')

# 对象配置模块
object_frame = ttk.LabelFrame(left_col, text="对象配置")
object_frame.pack(fill=tk.BOTH, expand=True, pady=10)

# 改为下拉框
entity_var = tk.StringVar(value='19')  # 默认值设为19
entity_combobox = ttk.Combobox(
    object_frame, textvariable=entity_var,
    values=['19', '410'], state='readonly'
)
entity_combobox.pack(pady=5)

data_id_label = ttk.Label(object_frame, text="数据ID:")
data_id_entry = ttk.Entry(object_frame, textvariable=data_id_var, width=20)
data_id_label.pack(pady=5)
data_id_entry.pack(pady=5)

# 右侧参数区
right_col = ttk.Frame(main_frame, width=400)
right_col.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

# 参数配置模块
param_frame = ttk.LabelFrame(right_col, text="参数配置")
param_frame.pack(fill=tk.BOTH, expand=True, pady=10)

param_type_combobox = ttk.Combobox(
    param_frame, textvariable=param_type_var,
    values=['quantity', 'unitPrice', 'priceTotal', 'unitQuantity', 'effectiveQuantity','discount']
)
param_type_combobox.pack(pady=5)

value_label = ttk.Label(param_frame, text="参数值:")
value_entry = ttk.Entry(param_frame, textvariable=value_var, width=20)
value_label.pack(pady=5)
value_entry.pack(pady=5)

# 操作按钮区
button_frame = ttk.Frame(main_frame, padding="10 0")
button_frame.pack(fill=tk.X)

generate_btn = ttk.Button(button_frame, text="生成URL", command=generate_url, padding=(8,4))
copy_btn = ttk.Button(button_frame, text="复制URL", command=copy_url, padding=(8,4))
generate_btn.pack(side=tk.LEFT, anchor='nw')
copy_btn.pack(side=tk.LEFT, anchor='nw')

# 结果展示区（支持换行显示）
result_text = tk.Text(
    main_frame, height=15, width=60, wrap='word',
    borderwidth=2, relief='sunken', background='#f8f9fa',
    font=('Arial', 10)
)
result_text.pack(fill=tk.BOTH, expand=True, pady=10)

# 绑定事件：环境选择改变时更新租户ID默认值
def update_tenant_entry(event):
    if env_var.get() == 'cd':
        tenant_entry.insert(0, '2245451914199072')
    else:
        tenant_entry.delete(0, tk.END)

env_combobox.bind('<<ComboboxSelected>>', update_tenant_entry)

if __name__ == "__main__":
    root.mainloop()